package com.liuzh.fitnessplan.activity

import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.util.Log
import android.view.View
import android.widget.ProgressBar
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.room.Room
import com.liuzh.fitnessplan.R
import com.liuzh.fitnessplan.base.BaseActivity
import com.liuzh.fitnessplan.database.Database
import com.liuzh.fitnessplan.database.bean.User
import com.liuzh.fitnessplan.databinding.ActivityRegisterBinding
import com.liuzh.fitnessplan.tools.ActivitysManager
import com.liuzh.fitnessplan.tools.RoomDatabaseUtil

class RegisterActivity : BaseActivity() {
    private lateinit var bind : ActivityRegisterBinding
    private lateinit var db : Database
    private lateinit var dialog : AlertDialog
    private var canBack = true
    private lateinit var handler : Handler
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        bind = ActivityRegisterBinding.inflate(layoutInflater)
        setContentView(bind.root)
        Log.d("RegisterActivity","${ActivitysManager.instance.getTopActivity()}")
        init()
        getDatabase()
        initListener()
    }
    //处理注册数据
    private fun init() {
        //数据加载Dialog
       dialog = AlertDialog.Builder(this)
            .setView(View.inflate(this, R.layout.loading_dialog,null)).create()
        handler =  @SuppressLint("HandlerLeak")
        object : Handler() {
            override fun handleMessage(msg: Message) {
                when(msg.what){
                    1 -> {
                        dialog.dismiss()
                        canBack = true
                        startActivity(Intent(this@RegisterActivity,MainActivity::class.java))
                        ActivitysManager.instance.finishActivity("LoginActivity")
                        finish()
                    }

                    2 ->{
                        Toast.makeText(this@RegisterActivity,"账号已存在",Toast.LENGTH_SHORT).show()
                        dialog.dismiss()
                        canBack = true
                    }

                }
            }
        }
    }

    private fun initListener() {
        bind.buttonRegister.setOnClickListener {
            if(bind.textRegisterAccount.text.toString() == ""){
                Toast.makeText(this,"账号不能为空",Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            if(bind.textRegisterAccount.text.toString().length < 6){
                Toast.makeText(this,"账号为6位到10位",Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            if(bind.textRegisterPasswd.text.toString() == ""){
                Toast.makeText(this,"密码不能为空",Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            if(bind.textRegisterPasswd.text.toString().length < 6){
                Toast.makeText(this,"密码为6位到15位",Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            val account = bind.textRegisterAccount.text.toString().toInt()
            val passwd = bind.textRegisterPasswd.text.toString()

            dialog.show()
            canBack = false
            Thread {

                val msg = Message()
                msg.what = register(account,passwd)
                handler.sendMessageDelayed(msg,500)
            }.start()
        }
    }
    //使Back键无效
    override fun onBackPressed() {
        if (canBack){
            super.onBackPressed()
        }else{
            return
        }
    }
    //获取Database实例
    private fun getDatabase(){
        db = RoomDatabaseUtil.instance.getDatabase(this)
    }

    private fun register(sAccount : Int , sPasswd : String) : Int{
        val user = User(sAccount,sPasswd)
        if(db.userDao().haveAccount(sAccount).isEmpty()){
            db.userDao().addNewUser(user)
            loginInfo(sAccount,true)
            return 1
        }
        return 2
    }


    @SuppressLint("CommitPrefEdits")
    private fun loginInfo(userName : Int, isLogin : Boolean){
        val sharedPreferences = getSharedPreferences("appInfo", Context.MODE_PRIVATE)
        val spEdit = sharedPreferences.edit()
        spEdit.putInt("userId",userName)
        spEdit.putBoolean("isLogin", isLogin)
        spEdit.apply()
    }

}
